import { ExceptionFilter, Catch, HttpException, ArgumentsHost } from "@nestjs/common";
import { ApiException } from "../exception/api.exception";
import { MyLogger } from "../logger/log.service";

@Catch(HttpException)
export class HttpExceptionFilters implements ExceptionFilter {
    catch(exception,host:ArgumentsHost){
        const ctx = host.switchToHttp();
        const response = ctx.getResponse();
        const request = ctx.getRequest();
        const status = exception.getStatus();
        const myLogger = new MyLogger();

        myLogger.log("错误抛出：" + JSON.stringify(exception));

        if(exception instanceof ApiException){
            response.status(status).json({
                code:exception.getErrorCode(),
                message:exception.getErrorMessage(),
                data:{
                    path:request.url,
                    date:new Date().toLocaleDateString()    
                }
            })
        } else{
             response.status(status).json({
                code:status,
                message:exception.message.message || exception.message,
                data:{
                    path:request.url,
                    date:new Date().toLocaleDateString()    
                }
            })
        }
    }
}